package client

import (
	"github.com/urfave/cli/v2"
	"gluenet/internal/client/create"
	del "gluenet/internal/client/delete"
	"gluenet/internal/client/describe"
	"gluenet/internal/client/get"
	"gluenet/pkg/log"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"os"
)

var Cli *cli.App

func init() {
	Cli = &cli.App{
		// 加载配置文件，将配置文件里面的信息存储在 cli.Context中
		Flags: []cli.Flag{
			// 配置文件路径
			&cli.StringFlag{
				Name:        "cache",
				Usage:       "the cache file to save info",
				EnvVars:     []string{"GLUE_CACHE"},
				DefaultText: "../../configs/cli_cache.yml",
			},
		},
		Before: loadConfigAndCache,
		Commands: []*cli.Command{
			{
				Name:  "login",
				Usage: "login gluenet system",
				// 将登录信息通过 cli.Context存储到配置文件中
				After: saveCache,
				Flags: []cli.Flag{
					&cli.StringFlag{Name: "user", Aliases: []string{"u"}},
					&cli.StringFlag{Name: "passwd", Aliases: []string{"p"}},
				},
				Action: login,
			},
			{
				Name:   "env",
				Usage:  "gluecli config env",
				Action: env,
			},
			{
				Name:        "get",
				Usage:       "get the resources",
				Subcommands: get.GetCmd(),
			},
			{
				Name:        "describe",
				Usage:       "describe resources detail",
				Subcommands: describe.GetCmd(),
			},
			{
				Name:        "create",
				Usage:       "create resource",
				Subcommands: create.GetCmd(),
			},
			{
				Name:        "delete",
				Usage:       "delete resource",
				Subcommands: del.GetCmd(),
			},
			{
				Name:   "logs",
				Usage:  "show object logs",
				Action: logShow,
			},
			{
				Name:   "top",
				Usage:  "show object top metrics",
				Action: top,
			},
		},
	}
}

func loadConfigAndCache(ctx *cli.Context) error {
	config := os.Getenv("GLUE_CONFIG")
	if config == "" {
		log.Infof("need GLUE_CONFIG path in env")
	}

	bts, err := ioutil.ReadFile(config)
	if err != nil {
		return err
	}
	var cfg = make(map[string]string)
	if err = yaml.Unmarshal(bts, &cfg); err != nil {
		return err
	}
	for k, v := range cfg {
		ctx.Set(k, v)
	}

	cache := os.Getenv("GLUE_CACHE")
	bts2, err := ioutil.ReadFile(cache)
	if err == nil {
		var che = make(map[string]string)
		if err = yaml.Unmarshal(bts2, &che); err != nil {
			return err
		}
		for k, v := range che {
			ctx.Set(k, v)
		}
	}
	return nil
}

func saveCache(ctx *cli.Context) error {
	return nil
}
